<template>
	<view class="elevator" @click="toDetail" :style="{
		paddingTop: elevator.index === 0 ? '0px' : '30rpx',
		borderBottom: last ? 'none' : ' 2rpx solid #eee',
	}">
		<!-- 超时的标签显示 S -->
		<view class="timeout" v-if="[2, 3].includes(elevator.typeStatus) && elevator.status < 5 && preventionShow">
			<image v-if="[1, 4, 5, -1].includes(userWxArriveStatus.status)" src="/static/images/maintain/funnel.png">
			</image>
			<image v-if="[2, 3].includes(userWxArriveStatus.status)" src="/static/images/maintain/funnelRED.png">
			</image>
			<text class="timeout-time" :class="{
				time1: [1].includes(userWxArriveStatus.status),
				time2: [2, 3].includes(userWxArriveStatus.status),
				time3: [4].includes(elevator.status) && [1].includes(userWxArriveStatus.status)
			}">
				<block v-if="estimatedTime">
					<text v-if="[2, 3].includes(userWxArriveStatus.status)">已超时</text>
					<text style="font-weight: 700;" v-if="[2].includes(userWxArriveStatus.status)"> {{ interValNoStr ||
						userWxArriveStatus.countdown }}
					</text>
					<text style="font-weight: 700;" v-else> {{ interVal || userWxArriveStatus.countdown }} </text>
				</block>
				<text v-if="estimatedTime && (userWxArriveStatus.status !== 1)">({{ estimatedTime }}前到达)</text>
			</text>
			<text class="timeout-text" :class="{
				text1: [1].includes(userWxArriveStatus.status),
				text2: [2, 3].includes(userWxArriveStatus.status),
				text3: [4, 5].includes(userWxArriveStatus.status),
				text4: [4].includes(elevator.status) && [1].includes(userWxArriveStatus.status),
			}" v-if="userWxArriveStatus.status">
				{{ ['准时达', '超时到达', '超时未达', '即将超时', '未及时出发'][userWxArriveStatus.status - 1] }}
			</text>
		</view>
		<!-- 超时的标签显示 E -->
		<view class="top">
			<view class="name" :style="{
				color:
					elevator.status == 7 ||
						(elevator.typeStatus == 3 && elevator.status == 5)
						? '#999'
						: '#333',
			}">
				{{ elevator.elevatorAddress }}
				<text class="tag red" v-if="elevator.elevatorIsStop != 1 && elevator.typeStatus != 3">停梯
				</text>
				<text class="tag red" v-if="elevator.typeStatus == 3">救援 </text>

				<text class="tag red" v-if="elevator.arrivalWarningDesc">
					{{ getErrorText() }}</text>

				<text class="tag red" v-if="elevator.typeStatus == 3 && elevator.status < 5">
					已报警{{ outTime }}</text>
				<!-- 事务紧急状态 -->

				<text class="tag" :style="{ color: '#e02020', borderColor: '#e02020' }"
					v-if="elevator.emerProcType == 1">
					{{ "非常紧急" }}
				</text>
				<text class="tag" :style="{ color: '#E02020', borderColor: '#E02020' }"
					v-if="elevator.reopenCount && elevator.typeStatus == 9 && elevator.planStatus != 4">
					{{ '重新打开' }}
				</text>
				<text class="tag"
					:style="{ color: elevator.redeployOverdueStatus == 2 ? '#FA6400' : '#E02020', borderColor: elevator.redeployOverdueStatus == 2 ? '#FA6400' : '#E02020' }"
					v-if="elevator.redeployOverdueStatus > 1 && elevator.typeStatus == 9">
					{{ elevator.redeployOverdueStatus == 2 ? '即将逾期' : '已逾期' }}
				</text>
				<text class="tag"
					:style="{ color: elevator.overdueType == 2 ? '#FA6400' : '#E02020', borderColor: elevator.overdueType == 2 ? '#FA6400' : '#E02020' }"
					v-else-if="elevator.overdueType > 1 && elevator.typeStatus == 9">
					{{ elevator.overdueType == 2 ? '即将逾期' : '已逾期' }}
				</text>
				<text v-if="isLocal"> </text>
			</view>

			<view class="handle" v-if="showTurnBtn" @click.stop="
				handleDelay(elevator, elevator.typeStatus, elevator.planId)
				">更多操作</view>
			<view class="score" v-if="elevator.scoreStatus == 1 && elevator.typeStatus == 1">
				{{ "工单评分:" + elevator.score + "分" }}
			</view>
		</view>
		<view class="detail" style="padding-bottom: 7rpx" v-if="elevator.typeStatus == 3">
			<view class="label" :style="{
				color:
					elevator.typeStatus == 3 && elevator.status == 5 ? '#999' : '#666',
			}">
				报警类型：
			</view>
			<view class="telName">
				<view>{{ elevator.trapType == 0 ? "困人" : "伤人" }}</view>
			</view>
		</view>
		<view class="detail" style="padding-top: 0" v-if="elevator.typeStatus == 3">
			<view class="label" :style="{
				color:
					elevator.typeStatus == 3 && elevator.status == 5 ? '#999' : '#666',
			}">
				报警备注：
			</view>
			<view class=" " style="flex: 1">
				{{ elevator.trapDesc || "无" }}
			</view>
		</view>
		<view class="detail" style="padding-top: 0" v-if="elevator.typeStatus == 3 && showBtn">
			<view class="label" :style="{
				color:
					elevator.typeStatus == 3 && elevator.status == 5 ? '#999' : '#666',
			}">
				报警时间：
			</view>
			<view class=" " style="flex: 1">
				{{ elevator.createTime || "" }}
			</view>
		</view>
		<!-- 这里展示小标签保养,维修,配件 -->
		<view class="detail" v-if="elevator.typeStatus !== 3" :style="{
			color:
				elevator.status === 4 ||
					elevator.status === 7 ||
					(elevator.typeStatus == 3 && elevator.status == 5)
					? '#999'
					: '#666',
		}">
			<!-- 保养不显示标题 -->
			<view class="labelName" v-if="elevator.typeStatus !== 1">{{ typeStatusMap[elevator.typeStatus] }}: </view>

			<view class="telName">
				<view v-if="elevator.typeStatus === 1 && planCheckNamesArray">
					<!-- 我的任务 -->
					<tags-component :label="`${typeStatusMap[elevator.typeStatus]}：`"
						:templateNames="planCheckNamesArray" displayCount="8" />
				</view>
				<view v-if="elevator.typeStatus === 4" class="problemItem">
					更换配件</view>
				<view v-if="elevator.typeStatus === 5" class="problemItem">事务工单</view>
				<view v-if="elevator.typeStatus === 6" class="problemItem">{{ ['保养质检', '重复故障质检', '维保移交质检',
					'安装移交质检', '常规质检'][elevator.checkType - 1] || "质量检查" }}</view>
				<view v-if="elevator.typeStatus === 9" class="problemItem">
					整改工单</view>
				<view v-if="elevator.typeStatus === 2 && elevator.malPartsNames">
					{{ sliceStr(elevator.malPartsNames) }}
					<text v-if="elevator.malFloorStandNames">({{ elevator.malFloorStandNames.replaceAll(',', '>')
					}})</text>
				</view>
				<view v-else-if="elevator.typeStatus === 2 && elevator.problemItemNames" class="problemItemBox">
					<view v-for="(v, idx) in elevator.problemItemNames" :key="idx" class="problemItem">{{ v }}
					</view>
				</view>
				<view v-else-if="elevator.typeStatus === 2">--</view>
				<!-- 维修标签 -->
			</view>
		</view>
		<!-- 事务工单描述 -->
		<view class="desc" v-if="elevator.typeStatus === 5 || elevator.typeStatus == 6">
			<view class="desc_left">任务描述:</view>
			<!-- <view class="desc_right">{{ elevator.affairDesc.replaceAll('&gt;','>') || "无" }}</view> -->
			<view class="desc_right">{{ affairDesc || "无" }}</view>
		</view>

		<!-- 保养整改工单 -->
		<view class="desc" v-if="elevator.typeStatus === 9">
			<view class="desc_left">截止日期:</view>
			<view class="desc_right">{{ elevator.redeployFinishDate ? elevator.redeployFinishDate :
				elevator.planFinishDate ?
					elevator.planFinishDate.split(' ')[0].replaceAll('-', '/') :
					'-' }}</view>
		</view>
		<view class="partsLabel" v-if="elevator.typeStatus === 4">
			<text v-for="(name, i) in partsNameFormat(elevator.partsName)" :key="i">{{ name || "--" }}
				<!--        <text v-if="elevator.floorStandNames">({{ elevator.floorStandNames.replaceAll(',', '>') }})</text> -->
			</text>
			<text v-if="elevator.partsNum">数量:{{ elevator.partsNum || "--" }}</text>
		</view>
		<view class="detail_bottom">
			<view class="detail_bottom_left" :style="{
				width:
					elevator.deferType === 1 || elevator.deferType === 5
						? '470rpx'
						: '',
			}">
				<image v-if="elevator.typeStatus == 1" :src="statusMap[elevator.status.toString()].icon"></image>
				<image v-if="elevator.typeStatus == 4" :src="partMap[elevator.status.toString()].icon"></image>
				<image v-if="elevator.typeStatus == 2" :src="repairStatusMap[elevator.status.toString()].icon"></image>
				<image v-if="elevator.typeStatus == 3" :src="rescueStatus[elevator.status.toString()].icon"></image>
				<image v-if="elevator.typeStatus == 5 || elevator.typeStatus == 6 || elevator.typeStatus == 9"
					:src="swMap[elevator.status.toString()].icon">
				</image>

				<view v-if="elevator.typeStatus == 1" class="status"
					:style="{ color: statusMap[elevator.status.toString()].color }">{{ elevator.statusName }}</view>
				<view v-if="elevator.typeStatus == 2" class="status"
					:style="{ color: repairStatusMap[elevator.status.toString()].color }">{{ elevator.statusName }}
				</view>
				<!-- 配件 -->
				<view v-if="elevator.typeStatus == 4" class="status"
					:style="{ color: partMap[elevator.status.toString()].color }">{{ elevator.statusName }}</view>
				<!-- 救援 -->
				<view v-if="elevator.typeStatus == 3" class="status"
					:style="{ color: rescueStatus[elevator.status.toString()].color }">{{ elevator.statusDesc ||
						elevator.statusName
					}}</view>
				<!-- 事务 -->
				<view v-if="elevator.typeStatus == 5 || elevator.typeStatus == 6 || elevator.typeStatus == 9"
					class="status" :style="{ color: swMap[elevator.status.toString()].color }">
					{{ elevator.statusDesc || elevator.statusName }}</view>

				<view class="error red" v-if="elevator.timeliness && elevator.typeStatus == 1" style="border: 0">
					{{ elevator.timeliness }}</view>
				<view class="error" :class="[elevator.overdueType === 2 ? 'yellow' : 'red']"
					v-if="[2, 3].includes(elevator.overdueType) && elevator.typeStatus == 1">{{ elevator.overdueTypeName
						|| ""
					}}
				</view>
				<view class="error red" v-if="elevator.deferType === 1 || elevator.deferType === 5">{{
					elevator.deferType === 1
						?
						"已延期" : "特殊延期" }}
				</view>
				<view class="error yellow" v-if="elevator.workMinuteName !== null && elevator.typeStatus === 1">{{
					elevator.workMinuteName }}</view>
			</view>
			<view class="menberName" v-if="!elevator.signUsers || elevator.signUsers.length <= 2">
				<view v-for="(e, index) in elevator.signUsers" :key="index" :class="['menber']" :style="{
					background: !e.isPlanStatus
						? '#b9b9b9'
						: userinfo.nick_name === e.userName
							? '#0091ff'
							: '#00C6C0',
				}">
					{{
						e.userName && e.userName.length > 2
							? e.userName.slice(-2)
							: e.userName
					}}
				</view>
			</view>

			<zb-tooltip @handchange="handchange($event)" :items="elevator" @click.stop v-else placement="bottom"
				background="#fff" right="26" color="#333" :showIcon="false">
				<view class="menberName">
					<view v-for="(user, uIdx) in elevator.signUsers.slice(0, 2)" :key="uIdx" :class="['menber']" :style="{
						background: !user.isPlanStatus
							? '#b9b9b9'
							: userinfo.nick_name === user.userName
								? '#0091ff'
								: '#00C6C0',
					}">
						{{
							user.userName && user.userName.length > 2
								? user.userName.slice(-2)
								: user.userName
						}}
					</view>
					<image v-if="elevator.signUsers.length > 2" :style="usermore ? 'transform: rotate(180deg);' : ''"
						src="@/static/images/down.png" mode=""></image>
				</view>
				<view class="userlist" slot="content">
					<view v-for="(user, uIdx) in elevator.signUsers" :key="uIdx" class="userlist-item">
						<view :class="['menber']" :style="{
							background: !user.isPlanStatus
								? '#b9b9b9'
								: userinfo.nick_name === user.userName
									? '#0091ff'
									: '#00C6C0',
						}">
							{{
								user.userName && user.userName.length > 2
									? user.userName.slice(-2)
									: user.userName
							}}
						</view>
						<view class="userlist-item-name"
							:style="!user.isPlanStatus ? 'color: #999999;' : 'color: #333'">
							{{ user.userName }}
						</view>
					</view>
				</view>
			</zb-tooltip>
		</view>

		<view class="detail-btn" v-if="showBtn && elevator.status == 3" @click.stop="rescueArrive(elevator)">确认到达</view>
		<view class="detail-btn" v-if="showBtn && elevator.status != 3">查看任务</view>
		<!-- 延期保养对话框start -->
		<uni-popup ref="deferredPopup">
			<view class="popup">
				<view class="title">延期保养</view>
				<view class="content">
					<view>此任务将推迟到</view>
					<view class="delay_date">
						<text>{{ tomorrowDate + "(明天)" }}</text>
						执行
					</view>
					<view class="delay_detail">
						<view>{{ elevator.buildingName + elevator.elevatorAddress }}</view>
						<view>{{ contentList.join(",").replace(/,/g, "+") }}</view>
					</view>
				</view>
				<view class="bottom">
					<view @click="$refs.deferredPopup.close()">取消</view>
					<view class="comfire" @click="rescueComfire">确认</view>
				</view>
			</view>
		</uni-popup>
		<!-- 延期保养对话框end -->
	</view>
</template>

<script>
import { mapState } from 'vuex';
import { formatTime, timeDiffFn, getlocalinfo } from '@/utils/utils.js';
import { setRescue } from '@/apis/rescue.js';
import { getContent } from '@/apis/index.js';
import tagsComponent from '@/components/tagsComponents/index';
import { rescueArrive } from '@/apis/elevator.js';
import { getDistance } from '@/utils/tools.js';

import dayjs from 'dayjs';
export default {
	components: { tagsComponent },
	props: {
		showBtn: Boolean,
		last: Boolean,
		elevator: {
			type: Object,
		},
	},
	data() {
		return {
			usermore: false,
			typeStatusMap: {
				1: '保养',
				2: '维修',
				3: '救援',
				4: '配件',
				5: '工单类型',
				6: '工单类型',
				9: '工单类型',
			},
			formatTime: formatTime,
			rescueStatus: {
				// 救援状态
				1: {
					text: '调度中',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				2: {
					text: '待开始',
					color: '#F7B500',
					icon: '/static/images/index/3.png',
				},
				3: {
					text: '已出发',
					color: '#F7B500',
					icon: '/static/images/index/3.png',
				},
				4: {
					text: '已到达',
					color: '#FA6400',
					icon: '/static/images/index/6.png',
				},
				5: {
					text: '已救援',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
				6: {
					text: '已撤回',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
			},
			statusMap: {
				1: {
					text: '待开始',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				2: {
					text: '进行中',
					color: '#0091ff',
					icon: '/static/images/index/2.png',
				},
				3: {
					text: '提交任务',
					color: '#F7B500',
					icon: '/static/images/index/3.png',
				},
				4: {
					text: '签字完成',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
				5: {
					text: '维保签字',
					color: '#FA6400',
					icon: '/static/images/index/5.png',
				},
			},

			repairStatusMap: {
				1: {
					text: '待处理',
					color: '#F7B500',
					icon: '/static/images/index/3.png',
				},
				2: {
					text: '待开始',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				3: {
					text: '进行中',
					color: '#0091ff',
					icon: '/static/images/index/2.png',
				},
				4: {
					text: '已完成',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
				5: {
					text: '已关闭',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
				6: {
					text: '签字完成',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
			},
			partMap: {
				1: {
					text: '待审批',
					color: '#F7B500',
					icon: '/static/images/index/3.png',
				},
				2: {
					text: '待报价',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				3: {
					text: '待发货',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				4: {
					text: '待分配',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				5: {
					text: '待开始',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				6: {
					text: '更换中',
					color: '#0091ff',
					icon: '/static/images/index/2.png',
				},
				7: {
					text: '已完成',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
				8: {
					text: '已关闭',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
				9: {
					text: '已撤回',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
			},
			swMap: {
				2: {
					text: '待开始',
					color: '#16BF99',
					icon: '/static/images/index/1.png',
				},
				3: {
					text: '进行中',
					color: '#0091ff',
					icon: '/static/images/index/2.png',
				},
				4: {
					text: '已完成',
					color: '#999',
					icon: '/static/images/index/4.png',
				},
			},
			tomorrowDate: formatTime(new Date().getTime() + 24 * 60 * 60 * 1000),
			contentList: [],
			timer: null,
			secondTime: 0,
			timeVal: null,
			interVal: '',
			estimatedTime: '',
			userWxArriveStatus: {},
			showEstimatedTime: false,// 用于只显示当天的时间标签
			preventionShow: true, // 用于没有时间状态和预计时间小于北京时间显示 默认true
			interValNoStr: '',// 用于准时达超时达到时间显示
		};
	},
	watch: {
		elevator(val) {
			this.setTimer();
		},
	},
	computed: {
		...mapState('user', ['userinfo']),
		...mapState('system', ['onlineStatus']),// 离线状态 ture 在线
		isLocal() {
			return false;
		},
		showTurnBtn() {
			let flag = false;
			if (this.elevator.auditType === 1) {
				// 非年审梯
				// 如果是待处理//非年审梯
				if (
					this.elevator.status === 1 &&
					(!this.elevator.overdueName || this.elevator.overdueName == '及时')
				) {
					flag = true;
				}
			} else {
				// 如果是待处理//年审梯
				if (
					this.elevator.status === 1 &&
					(!this.elevator.overdueName || this.elevator.overdueName == '及时')
				) {
					flag = true;
					// 年审梯 已延期特殊延期过 不显示更多按钮
					if (this.elevator.planDate) {
						if (
							(this.elevator.deferType === 1 ||
								this.elevator.deferType === 5) &&
							new Date(this.elevator.planDate.replaceAll('-', '/')).getTime() /
							1000 ===
							new Date(dayjs().format('YYYY/MM/DD')).getTime() / 1000
						) {
							flag = false;
						}
					}
				}
			}

			return flag;
		},
		outTime() {
			return this.formateSeconds(this.secondTime);
		},
		affairDesc() {
			if (this.elevator.affairDesc) {
				return this.elevator.affairDesc.split(' &gt; ').join('>');
			} else {
				return '';
			}
		},
		planCheckNamesArray() {
			return (this.elevator && this.elevator.planCheckName)
				? this.elevator.planCheckName.split(',')
				: [];
		},
	},
	created() {
		this.setTimer();
		this.fetureTime();
		this.intervalTime();
		this.fetureRescueTime();
	},
	mounted() {
		uni.$on('myTaskHide', () => {
			if (this.timeVal) {
				clearInterval(this.timeVal);
			}
		});
	},
	onHide() {
		if (this.timer) {
			clearInterval(this.timer);
			this.timer = null;
		}
	},
	onUnload() {
		if (this.timer) {
			clearInterval(this.timer);
			this.timer = null;
		}
	},
	methods: {
		partsNameFormat(name) {
			if (!name) {
				return [];
			}
			let partsName = name.replaceAll('&amp;&amp;', '>');
			let result = [];
			if (partsName) {
				result = partsName.split(',').map(v => v.split('>')[v.split('>').length - 1]);
			}
			return result || [];
			// return name.replaceAll('&amp;&amp;','>');
		},
		getErrorText() {
			let item = this.elevator;
			if (item.arrivalWarning == 3) {
				return (item.maximumType == 1 ? '超项目规定时长到达' : '超时30分钟到达');
			}

			if (item.arrivalWarning == 2) {
				return (item.maximumType == 1 ? '超项目规定时长未达' : '超时30分钟未达');
			}

			if (item.arrivalWarning == 1) {
				return (item.maximumType == 1 ? '即将超项目规定时长到达' : '即将超30分钟到达');
			}
			return item.arrivalWarningDesc || '';
		},

		// 救援任务确认到达
		async rescueArrive(elevator) {
			uni.showModal({
				title: '提示',
				content: '是否确认已到达项目地点？',
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '提交中',
							mask: true,
						});

						let localInfo = await this.getLocalInfo();
						if (!localInfo.latitude) {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: '请打开定位，再签到',
								showCancel: false,
							});
							return;
						}
						// 计算是否范围内打卡
						let distance = getDistance(
							localInfo.latitude,
							localInfo.longitude,
							elevator.latitude,
							elevator.longitude
						);
						let address = {};
						try {
							address = await getlocalinfo(localInfo.latitude, localInfo.longitude);
							console.log('address', address);
						} catch (error) {
							console.log('error', error);
						}

						let signStatus = 1;
						if (!localInfo.latitude) {
							// this.locationError = '无定位';
						}
						if (distance > this.$config.maxDistance) {
							signStatus = 2;
							// this.locationError = '偏离项目定位';
						} else {
							// this.locationError = '正常';
						}

						rescueArrive({
							signStatus,
							locationAddress: address.result.address,
							latitude: localInfo.latitude,
							longitude: localInfo.longitude,
							planId: elevator.planId,
							userId: this.userinfo.user_id,
						}).then(() => {
							// 方案1：使用$emit通知父组件更新数据（推荐）
							this.$emit('updateElevatorStatus', {
								planId: elevator.planId,
								status: 4,
								statusDesc: '已到达'
							});

							uni.hideLoading();
							uni.showToast({
								title: '提交成功',
								icon: 'none'
							});
						});
					}
				}
			});
		},
		sliceStr(str) {
			if (str.length >= 20) {
				str = str.slice(0, 20) + '...';
			}
			return str;
		},
		setTimer() {
			if (this.elevator.typeStatus == 3 && this.elevator.status < 5) {
				let now = new Date(
					this.elevator.serviceDate.replaceAll('-', '/')
				).getTime();
				let createTime = new Date(
					this.elevator.createTime.replaceAll('-', '/')
				).getTime();
				let secondTime = ((now - createTime) / 1000).toFixed(0);
				this.secondTime = secondTime;
				now = null;
				createTime = null;
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
				this.timer = setInterval(() => {
					this.secondTime++;
				}, 1000);
			}
		},
		// 将秒转化为时分秒
		formateSeconds(endTime) {
			let secondTime = parseInt(endTime); // 将传入的秒的值转化为Number
			let min = 0; // 初始化分
			let h = 0; // 初始化小时
			let result = '';
			if (secondTime > 60) {
				// 如果秒数大于60，将秒数转换成整数
				min = parseInt(secondTime / 60); // 获取分钟，除以60取整数，得到整数分钟
				secondTime = parseInt(secondTime % 60); // 获取秒数，秒数取佘，得到整数秒数
				if (min > 60) {
					// 如果分钟大于60，将分钟转换成小时
					h = parseInt(min / 60); // 获取小时，获取分钟除以60，得到整数小时
					min = parseInt(min % 60); // 获取小时后取佘的分，获取分钟除以60取佘的分
				}
			}
			if (h.toString().padStart(2, '0') == '00') {
				result = `${min.toString().padStart(2, '0')}:${secondTime
					.toString()
					.padStart(2, '0')}`;
			} else {
				result = `${h.toString().padStart(2, '0')}:${min
					.toString()
					.padStart(2, '0')}:${secondTime.toString().padStart(2, '0')}`;
			}

			return result;
		},

		handchange(val, index) {
			this.usermore = val;
		},
		toDetail() {
			if (this.elevator.typeStatus == 1) {
				const ids = uni.getStorageSync('localPlanIds') || '';
				if (!this.onlineStatus && ids.indexOf(this.elevator.planId) == -1) {
					uni.showToast({
						title: '该保养任务未成功加载，请检查网络后再试',
						icon: 'none'
					});
					return;
				}
			} else {
				if (!this.onlineStatus) {
					uni.showToast({
						title: '当前网络离线，请检查网络后再试',
						icon: 'none'
					});
					return;
				}
			}

			uni.showLoading({
				title: '加载中',
			});
			uni.setStorage({
				key: 'offline_detail',
				data: this.elevator,
				success: () => {
					console.log('查看工单详情', this.elevator);
					if (this.elevator.typeStatus == 2) {
						// 维修详情
						uni.navigateTo({
							url:
								'/subpages/repair/repariDetail?planId=' +
								this.elevator.planId +
								'&elevatorId=' +
								this.elevator.elevatorId,
						});
					}
					// 配件更换
					if (this.elevator.typeStatus == 4) {
						uni.navigateTo({
							url: `/subpages/workOrders/partOrder?planId=${this.elevator.planId}&elevatorId=${this.elevator.elevatorId}`,
						});
					}
					if (this.elevator.typeStatus == 1) {
						// 保养详情
						uni.navigateTo({
							url: `/subpages/workOrders/detail?planId=${this.elevator.planId}&elevatorId=${this.elevator.elevatorId}`,
						});
					}

					if (this.elevator.typeStatus == 3) {
						uni.navigateTo({
							url: `/subpages/rescue/rescueDetail?planId=${this.elevator.planId
								}&elevatorId=${this.elevator.elevatorId > 0 ? this.elevator.elevatorId : ''
								}`,
						});
					}
					//   事务工单
					if (this.elevator.typeStatus == 5) {
						uni.navigateTo({
							url:
								'/subpages/repair/affair/affairDetail?planId=' +
								this.elevator.planId +
								'&elevatorId=' +
								this.elevator.elevatorId,
						});
					}
					// 质检工单
					if (this.elevator.typeStatus == 6) {
						uni.navigateTo({
							url:
								'/subpages/quality/qualityDetail?planId=' +
								this.elevator.planId +
								'&elevatorId=' +
								this.elevator.elevatorId,
						});
					}

					if (this.elevator.typeStatus == 9) {
						uni.navigateTo({
							url:
								'/subpages/correction/detail?planId=' +
								this.elevator.planId +
								'&elevatorId=' +
								this.elevator.elevatorId,
						});
					}

					this.$emit('toDetail', this.elevator);
				},
				complete: (complete) => {
					uni.hideLoading();
				},
			});
		},
		// 延迟保养
		handleDelay(item, type, planId) {
			console.log(item);
			// 只有自己的任务
			if (this.elevator.userIds) {
				let elevatorArr = this.elevator.userIds.split(',');
				let result = elevatorArr.some((item) => item === this.userinfo.user_id);
				if (!result) {
					uni.showModal({
						title: '提示',
						content: '你没有权限操作该任务',
						showCancel: false,
						confirmText: '我知道了',
						success: (res) => {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						},
					});
					return;
				}
			}

			let arr = ['延期保养', '提前保养'];
			if (
				item.status === 1 &&
				(!item.overdueName || item.overdueName == '及时')
			) {
				// 待开始+未逾期
				if (item.auditType === 2) {
					// 年审类型
					arr = ['延期保养'];
					if (item.deferType === 5 || item.deferType === 1) {
						// 被特殊年审延期过后
						arr = ['提前保养'];
					}
				}
				if (item.auditType === 1) {
					// 非年审类型
					if (item.planDate) {
						if (
							new Date(item.planDate.replaceAll('-', '/')).getTime() / 1000 <=
							new Date(dayjs().format('YYYY/MM/DD')).getTime() / 1000
						) {
							// 小于等于今天任务的日期只显示延期
							arr = ['延期保养'];
						}
					}
				}
				uni.showActionSheet({
					itemList: arr,
					success: async (res) => {
						let needObj = {
							planId: item.planId,
							buildingAddress: item.buildingName + item.elevatorAddress,
							planCheckName: item.planCheckName,
							planDate: item.planDate,
							auditType: item.auditType,
						};
						if (item.auditType === 1) {
							// 非年审
							let str = '';
							if (res.tapIndex === 0) {
								// 去延期保养页面
								str =
									'/pageModules/yearTrial/calendarEdit?needObj=' +
									JSON.stringify(needObj) +
									'&nums=' +
									1;
							}
							if (res.tapIndex === 1) {
								// 去提前保养页面
								str =
									'/pageModules/yearTrial/calendarEdit?needObj=' +
									JSON.stringify(needObj) +
									'&nums=' +
									2;
							}
							uni.navigateTo({
								url: str,
							});
						}
						if (item.auditType === 2) {
							// 年审
							if (res.tapIndex == 0 && arr[0] === '延期保养') {
								uni.navigateTo({
									url:
										'/pageModules/yearTrial/yearDelay?needObj=' +
										JSON.stringify(needObj),
								});
							}
							if (res.tapIndex == 0 && arr[0] === '提前保养') {
								uni.navigateTo({
									url:
										'/pageModules/yearTrial/calendarEdit?needObj=' +
										JSON.stringify(needObj) +
										'&nums=' +
										3,
								});
							}
						}
					},
					fail(res) { },
				});
			}

			// uni.showActionSheet({
			// 	itemList: [type == 1 ? '延期保养' : '转单'],
			// 	success: async res => {
			// 		if (res.tapIndex == 0) {
			// 			this.contentList = await this.fetchTemContent();
			// 			this.$refs.deferredPopup.open();
			// 		}
			// 	},
			// 	fail(res) {}
			// });
		},
		rescueComfire() {
			console.log(this.elevator.planId);
			setRescue({ id: this.elevator.planId, isDeferred: 1 }).then((res) => {
				// console.log(res,'延期保养')
				if (res) {
					uni.showToast({
						title: '延期成功',
						icon: 'none',
					});
					this.$refs.deferredPopup.close();
					this.$emit('update');
				}
			});
		},
		fetchTemContent() {
			return new Promise((resolve) => {
				getContent({ planId: this.elevator.planId })
					.then((res) => {
						// console.log(res,'res的值')
						resolve(res.data);
					})
					.catch((resolve) => {
						resolve([]);
					});
			});
		},
		planCheckNameToTags(str) {
			return str.split(',');
		},
		popUpHandler(status, params) {
			uni.$emit('tagsPoupTrigger', { status, ...params });
		},
		// 救援时间状态
		fetureRescueTime() {
			if (this.elevator.typeStatus == 3 && this.elevator.maximumArrivalTime) {
				const item = this.elevator;
				// 如果 maximumArrivalTime 为空，则用 createTime + 30 分钟
				let arrivalTimeStr = '';
				let arrival;
				if (!item.maximumArrivalTime && item.createTime) {
					const create = new Date(item.createTime.replace(/-/g, '/')).getTime();
					arrival = create + 30 * 60 * 1000;
					// 格式化为 'yyyy-MM-dd HH:mm:ss'
					const arrivalDate = new Date(arrival);
					const pad = n => n < 10 ? '0' + n : n;
					item.maximumArrivalTime =
						arrivalDate.getFullYear() + '-' +
						pad(arrivalDate.getMonth() + 1) + '-' +
						pad(arrivalDate.getDate()) + ' ' +
						pad(arrivalDate.getHours()) + ':' +
						pad(arrivalDate.getMinutes()) + ':' +
						pad(arrivalDate.getSeconds());
				}
				arrival = item.maximumArrivalTime ? new Date(item.maximumArrivalTime.replace(/-/g, '/')).getTime() : null;
				const now = Date.now();
				let diff = arrival ? Math.round((arrival - now) / 60000) : null;
				arrivalTimeStr = item.maximumArrivalTime ? item.maximumArrivalTime.slice(11, 16) : '--:--';
				if (diff !== null) {
					if (diff >= 0) {
						item.countdown = `剩余${diff}min`;
						item.timeStatus = 0;
					} else {
						const absDiff = Math.abs(diff);
						if (absDiff >= 60) {
							const h = Math.floor(absDiff / 60);
							const m = absDiff % 60;
							item.countdown = `${h}h${m}min`;
						} else {
							item.countdown = `${absDiff}min`;
						}
						item.timeStatus = 1;
					}
					item.arrivalTime = arrivalTimeStr;
				} else {
					item.countdown = '';
					item.arrivalTime = '';
				}
				this.userWxArriveStatus = item;
				this.estimatedTime = arrivalTimeStr || '';
			}
		},
		// 初始获取维修时间状态
		fetureTime() {
			if (this.elevator.typeStatus == 2 && this.elevator.signUsers && this.elevator.signUsers.length > 0) {
				this.userWxArriveStatus = this.elevator.signUsers.find(item => item.userId == this.userinfo.user_id) || {};
				this.userWxArriveStatus.status = Number(this.userWxArriveStatus.userWxArriveStatus);
				let str3 = this.userWxArriveStatus.planArriveDate?.substring(0, 4);
				this.estimatedTime = '';
				if (!['1970'].includes(str3)) {
					this.estimatedTime = this.userWxArriveStatus.planArriveDate?.slice(11).substring(0, 5);
				}
			}
		},
		// 对应时间状态与定时器
		intervalTime() {
			if (this.elevator.beijingDate && this.elevator.typeStatus == 2) {
				if (this.userWxArriveStatus.planArriveDate) {
					let nowTime = new Date(this.userWxArriveStatus.planArriveDate.replaceAll('-', '/')).getTime();
					let nowTime2 = new Date(this.userWxArriveStatus.planArriveDate.replaceAll('-', '/')).getTime();
					let nowTime3 = new Date(this.userWxArriveStatus.planArriveDate.replaceAll('-', '/')).getTime();
					let bgTime = new Date(this.elevator.beijingDate.replaceAll('-', '/')).getTime();

					let createTime = new Date((this.userWxArriveStatus.createTime || '').replaceAll('-', '/')).getTime();
					let signDate = new Date((this.userWxArriveStatus.signDate || '').replaceAll('-', '/')).getTime();
					let s1970 = (this.userWxArriveStatus.signDate || '').substring(0, 4);
					if (this.timeVal) {
						clearInterval(this.timeVal);
					}
					if ([1].includes(this.userWxArriveStatus.status)) {// 准时达
						if (s1970 !== '1970') {
							let resData = timeDiffFn(dayjs(signDate).format('YYYY-MM-DD HH:mm:ss'), 0, dayjs(createTime).format('YYYY-MM-DD HH:mm:ss'));
							this.interValNoStr = (resData.hours > 0 ? resData.hours + 'h' : '') + (resData.minutes > 0 ? resData.minutes + 'min' : '');
						}
					}
					if ([2].includes(this.userWxArriveStatus.status)) {// 超时达
						if (s1970 !== '1970') {
							let resDatas = timeDiffFn(dayjs(signDate).format('YYYY-MM-DD HH:mm:ss'), 0, dayjs(nowTime).format('YYYY-MM-DD HH:mm:ss'));
							this.interValNoStr = (resDatas.day > 0 && resDatas.hours > 0 ? resDatas.day + 'd' : '') + (resDatas.hours > 0 ? resDatas.hours + 'h' : '') + (resDatas.minutes >= 0 ? (resDatas.minutes + 1) + 'min' : '');
							if (this.elevator.status === 4) {// 已完成显示超时天数
								this.interValNoStr = (resDatas.day > 0 ? resDatas.day + 'd' : '') + (resDatas.hours > 0 ? resDatas.hours + 'h' : '') + (resDatas.minutes >= 0 ? (resDatas.minutes + 1) + 'min' : '');
							}
						}
					}
					// 没有时间状态和即将超时状态时 且 预计时间小于北京时间显示 不展示
					if ((this.userWxArriveStatus.status == -1 || this.userWxArriveStatus.status == 4) && nowTime < bgTime) {
						this.preventionShow = false;
					}
					if (s1970 == '1970') {// 未签到维修单开启定时器
						this.timeVal = setInterval(() => {
							if ([3].includes(this.userWxArriveStatus.status)) {// 超时未达
								nowTime2 -= 1000;
								let resTimeObj = timeDiffFn(dayjs(bgTime).format('YYYY-MM-DD HH:mm:ss'), 0, dayjs(nowTime2).format('YYYY-MM-DD HH:mm:ss'));
								this.interVal = (resTimeObj.day > 0 && resTimeObj.hours > 0 ? resTimeObj.day + 'd' : '') + (resTimeObj.hours > 0 ? resTimeObj.hours + 'h' : '') + (resTimeObj.minutes >= 0 ? (resTimeObj.minutes === 0 ? resTimeObj.minutes + 1 : resTimeObj.minutes) + 'min' : '');
							}
							if ([4, 5].includes(this.userWxArriveStatus.status) || this.userWxArriveStatus.status == -1) {// 即将超时 未及时到达
								if (nowTime >= bgTime) {// 预计时间大于当前时间
									nowTime -= 1000;
									let nowTimeObj = timeDiffFn(dayjs(nowTime).format('YYYY-MM-DD HH:mm:ss'), 0, dayjs(bgTime).format('YYYY-MM-DD HH:mm:ss'));
									this.interVal = (nowTimeObj.hours > 0 ? nowTimeObj.hours + 'h' : '') + (nowTimeObj.minutes >= 0 ? (nowTimeObj.minutes === 0 ? nowTimeObj.minutes + 1 : nowTimeObj.minutes) + 'min内' : '');
								}
								if (bgTime >= nowTime) {
									// nowTime3 -= 1000;
									// let bgTimeObj = timeDiffFn(dayjs(bgTime).format('YYYY-MM-DD HH:mm:ss'),0,dayjs(nowTime3).format('YYYY-MM-DD HH:mm:ss'))
									// this.interVal = (bgTimeObj.hours > 0 ? bgTimeObj.hours+'h':'')+(bgTimeObj.minutes >= 0 ? (bgTimeObj.minutes === 0?bgTimeObj.minutes+1:bgTimeObj.minutes)+'min内':'')
									this.interVal = '';
								}
							}
						}, 1000);
					}
				}
			}
		},

		// restName(name) {
		//   let str = "";
		//   if (name) {
		//     str = name.split("&amp;&amp;");
		//   }
		//   return str[str.length - 1] || "";
		// },

	},
};
</script>

<style lang="scss" scoped>
.elevator {
	padding-bottom: 20rpx;
	border-bottom: 2rpx solid #eee;

	// padding-top: 30rpx;
	.top {
		display: flex;
		justify-content: space-between;

		// align-items: center;
		.handle {
			display: flex;
			// align-items: center;
			// padding: 0 20rpx;
			color: #999999;
			// flex: 1;
			justify-content: center;
			// border: 2rpx #d8d8d8 solid;
			padding: 2rpx 8rpx;
			font-size: 24rpx;
			border-radius: 8rpx;
			height: 31rpx;
			margin-top: 5rpx;
			// margin-right: 10rpx;
		}

		.score {
			color: #999;
			font-size: 24rpx;
			display: flex;
			flex: 1;
			align-items: center;
			justify-content: flex-end;
			height: 48rpx;
		}
	}

	.name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		display: flex;
		flex-wrap: wrap;
		align-items: center;

		// width: 466rpx;
	}

	.detail {
		width: 100%;
		font-size: 26rpx;
		color: #666666;
		padding: 14rpx 0;
		display: flex;
		align-items: baseline;

		.labelName {
			margin-right: 16rpx;
			color: #666;
		}

		.label {
			width: 140rpx;
			display: flex;
			align-items: center;
		}

		.telName {
			display: flex;
			flex-wrap: wrap;
			// width: 580rpx;
			flex: 1;

			.problemItemBox {
				display: flex;
				flex-wrap: wrap;
			}

			.problemItem {
				font-size: 24rpx;
				border: 2rpx solid #cccccc;
				border-radius: 20rpx;
				margin: 06rpx 12rpx;
				padding: 2rpx 8rpx;
				margin-top: 6rpx;
				margin-left: 0;
			}
		}

		image {
			width: 32rpx;
			height: 32rpx;
		}
	}

	.desc {
		display: flex;

		color: #666;
		font-size: 26rpx;
		margin-bottom: 16rpx;

		.desc_left {
			margin-right: 16rpx;
		}

		.desc_right {
			width: 520rpx;
			overflow: hidden;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			/* 设置最大显示行数 */
			-webkit-box-orient: vertical;
			text-overflow: ellipsis;
		}
	}

	.partsLabel {
		text {
			display: inline-block;
			background-color: #dcf0ff;
			padding: 4rpx 8rpx;
			margin-right: 20rpx;
			font-size: 24rpx;
			color: #0091ff;
			border-radius: 4rpx;
		}
	}

	.detail_bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;

		image {
			width: 32rpx;
			height: 32rpx;
			margin-right: 4rpx;
		}

		&_left {
			display: flex;
			font-size: 26rpx;
			align-items: center;
			// width: 470rpx;

			.status {
				color: #16bf99;
			}

			.error {
				margin-left: 12rpx;
				padding: 0rpx 8rpx;
				font-size: 24rpx;
				border-radius: 4rpx;
			}

			.red {
				color: #e02020;
				background: #ffe3e3;
				border: none !important;
			}

			.yellow {
				color: #fa6400;
				background: #ffefe3;
			}
		}
	}

	.menberName {
		display: flex;
		align-items: center;
		// flex: 1;
		justify-content: flex-end;
		flex-wrap: wrap;

		.menber {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 20rpx;
			width: 48rpx;
			height: 48rpx;
			border-radius: 50%;
			background-color: #0091ff;
			color: #fff;
			margin-left: 4rpx;
		}

		:nth-child(2n) {
			// background-color: #00c6c0;
		}

		.finish {
			// background: #b9b9b9;
		}
	}

	.tag {
		font-size: 24rpx;
		padding: 0rpx 9rpx;
		font-weight: normal;
		margin: 1px;
		margin-left: 12rpx;
		border-radius: 4rpx;
		line-height: 32rpx;
		height: 32rpx;
		white-space: nowrap;
		border: 2rpx solid transparent;
	}

	.red {
		color: #e02020;
		border: 2rpx solid #e02020;
	}

	.popup {
		padding: 24rpx 28rpx 0 28rpx;
		box-sizing: border-box;
		background-color: #fff;
		width: 506rpx;
		border-radius: 16rpx;

		.title {
			color: #333;
			font-size: 32rpx;
			font-weight: 500;
			padding-bottom: 20rpx;
		}

		.content {
			text-align: center;
			color: #333;
			margin-bottom: 38rpx;

			.delay_date {
				margin-bottom: 16rpx;
				font-size: 28rpx;

				text {
					color: #0091ff;
				}
			}

			.delay_detail {
				color: #999;
				font-size: 24rpx;
			}
		}

		.bottom {
			display: flex;
			border-top: 2rpx solid #f5f5f5;
			height: 76rpx;

			view {
				display: flex;
				flex: 1;
				justify-content: center;
				align-items: center;
				font-size: 28rpx;
				color: #999;
			}

			.comfire {
				color: #0091ff;
				border-left: 2rpx solid #f5f5f5;
			}
		}
	}

	.userlist {
		&-item {
			display: flex;
			align-items: center;
			width: 180rpx;
			margin-bottom: 17rpx;

			.menber {
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 20rpx;
				width: 48rpx;
				height: 48rpx;
				border-radius: 50%;
				background-color: #0091ff;
				color: #fff;
				margin-left: 4rpx;
				margin-right: 14rpx;
			}

			&-name {
				font-size: 24rpx;
				color: #333;
				overflow: hidden;
				flex: 1;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
		}

		&-item:last-child {
			margin-bottom: 0;
		}
	}
}

.timeout {
	display: flex;
	align-items: center;
	font-size: 24rpx;
	margin-bottom: 16rpx;

	image {
		width: 30rpx;
		height: 30rpx;
		// margin-right: 8rpx;
	}

	.timeout-time {
		color: #FA6400;
	}

	.time1 {
		color: #16bf99;
	}

	.time2 {
		color: #E02020;
	}

	.time3 {
		color: #999999;
	}

	.timeout-text {
		color: #FA6400;
		display: inline-block;
		padding: 0 4rpx;
		border-radius: 4rpx;
		background: #E3FFF6;
		margin-left: 4rpx;
	}

	.text1 {
		color: #16bf99;
		background: #E3FFF6;
	}

	.text2 {
		color: #E02020;
		background: #FFE3E3;
	}

	.text3 {
		color: #FA6400;
		background: #FFEFE3;
	}

	.text4 {
		color: #999999;
		background: #F1F1F1;
	}
}

.detail-btn {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 64rpx;
	background: #0091ff;
	border-radius: 4rpx;
	font-weight: bold;
	color: #fff;
	font-size: 26rpx;
	margin-top: 20rpx;
}
</style>
